//app.js
App({
  onLaunch: function(options) {

    // 登录
    wx.login({
      success: res => {
        // console.log("登录成功")
        // console.log(res.code)
        wx.request({
          url: 'https://api.weixin.qq.com/sns/jscode2session',
          data: {
            appid: "wx3f127364cc8c3dfc",
            secret: "b3a29f5477effcbd308e7ccfb122d1a9",
            grant_type: "authorization_code",
            js_code: res.code
          },
          success: res => {

            var sk = res.data.session_key
            // console.log(res.data.session_key)
            // 获取用户信息
            wx.getSetting({
              success: res => {
                if (res.authSetting['scope.userInfo']) {
                  // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                  wx.getUserInfo({
                    success: res => {
                      
                      // 可以将 res 发送给后台解码出 unionId
                      this.globalData.userInfo = res.userInfo
                      if (this.onUserInfoReady) this.onUserInfoReady()

                      // console.log(res.rawData, sk, res.encryptedData, res.iv)
                      // console.log(res.signature )

                      wx.request({
                        url: 'http://127.0.0.1:9999/jiemi',
                        data: {
                          appId: "wx3f127364cc8c3dfc",
                          sessionKey: sk,
                          encryptedData: res.encryptedData,
                          iv: res.iv
                        },
                        success: res => {
                          this.globalData.userInfo.openId = res.data.openId
                          
                          if (this.onOpenIdReady) this.onOpenIdReady(res.data.openId)
                          
                          // wx.request({
                          //   url: '/register',
                          //   data: {
                          //     nickname: this.globalData.userInfo.nickname,
                          //     faceimg: this.globalData.userInfo.imgurl,
                          //     userid: res.data.openId
                          //   },
                          //   success: res => {
                          //     console.log("注册成功")
                          //   }
                          // })
                        }

                      })
                    }
                  })
                }
              }
            })
          }
        })
      }
    })


  },
  globalData: {
    userInfo: null,
    openGId: -1
  }
})